﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using ZWFrameWork;

namespace View.Instant
{
    public enum LoginType
    {
        Reg = 0,
        Login = 1,
    }
    
    public class LoginView : View
    {
        //游客
        private GameObject mLogin_Panel;
        private InputField mLogin_InputPhone;
        private Button mLogin_btnLogin;
        private Button mLogin_btnRegister;
        private Button mLogin_btnGuest;

        //手机号码登录
        private GameObject mPhoneLogin_Panel;
        private Button mPhoneLogin_btnClose;
        private InputField mPhoneLogin_InputPhone;
        private InputField mPhoneLogin_InputPwd;
        private Button mPhoneLogin_btnForgetPwd;
        private Button mPhoneLogin_btnLogin;
        private Button mPhoneLogin_btnShowPwd;
        private GameObject mPhoneLogin_ShowPwd_Hide;
        private GameObject mPhoneLogin_ShowPwd_Show;
        
        //注册
        private GameObject mRegister_Panel;
        private Button mRegister_btnClose;
        private InputField mRegister_InputPhone;
        private InputField mRegister_InputPwd;
        private InputField mRegister_InputOpt;
        private Button mRegister_btnShowPwd;
        private Button mRegister_btnOpt;
        private GameObject mRegister_ClickOpt;
        private Text mRegister_txtOpt;
        private Button mRegister_btnRegister;
        private GameObject mRegister_ShowPwd_Hide;
        private GameObject mRegister_ShowPwd_Show;
        
        //找回密码
        private GameObject mFindPwd_Panel;
        private Button mFindPwd_btnClose;
        private InputField mFindPwd_InputPhone;
        private InputField mFindPwd_InputPwd;
        private InputField mFindPwd_InputOpt;
        private Button mFindPwd_btnShowPwd;
        private Button mFindPwd_btnOpt;
        private GameObject mFindPwd_ClickOpt;
        private Text mFindPwd_txtOpt;
        private Button mFindPwd_btnModify;
        private GameObject mFindPwd_ShowPwd_Hide;
        private GameObject mFindPwd_ShowPwd_Show;

        private GameObject Lamp;

        private Dropdown mdropdown;
        
        ///////////

        private string mPhone = "";
        private string mPhonePwd = "";
        private bool misTimeend = false;                             //结束了？

        float lamp_times = 0;

        /// <summary>
        /// 预加载
        /// </summary>
        public override void OnLoad()
        {
            base.OnLoad();
#if UNITY_EDITOR
            GlobalUserItem.szMachineID = "22222222887878788888888888888888888888888888781_102";
            //GlobalUserItem.szMachineID = "2222222288787558989";
#else
            if (PlayerPrefs.HasKey("UserMachineID"))
            {
                GlobalUserItem.szMachineID = PlayerPrefs.GetString("UserMachineID");
            }
            else
            {
                GlobalUserItem.szMachineID = UnityEngine.Random.Range(100000, 99999999999) + "";
                PlayerPrefs.SetString("UserMachineID", GlobalUserItem.szMachineID);
            }
#endif

            OnInitLogin();

            OnInitPhoneLogin();
            
            OnInitRegister();
            
            OnInitFindPwd();

#if !UNITY_EDITOR
// Debug.LogError("shibushidiyici===================================");
            if (GlobalUserItem.mBoolFirstOpenEnterLogin)
            {
                // PlayerPrefs.DeleteKey(GlobalUserItem.mPhoneKey);
                if (PlayerPrefs.HasKey(GlobalUserItem.mPhoneKey))
                {
                    if (PlayerPrefs.HasKey(GlobalUserItem.mPwdKey))
                    {
                        mPhone = PlayerPrefs.GetString(GlobalUserItem.mPhoneKey);
                        mPhonePwd = PlayerPrefs.GetString(GlobalUserItem.mPwdKey);
                        OnPhoneLogin(mPhone, mPhonePwd);
                    }
                }
                else
                {
                    Utils.StartCoroutine(GetAdjustInfo());
                }
            }
            GlobalUserItem.mBoolFirstOpenEnterLogin = false;
#endif
            //NetConfig.LOGIN_SERVER_URL = "ws://13.126.87.222:6301";
            //NetConfig.CHAT_SERVER_URL = "ws://13.126.87.222:6302";
            //NetConfig.PostEnvir = "https://front.apoiionnewgame.xyz";
            //NetConfig.ServerLink = 0;
            //GlobalUserItem.PostEnvir = "https://front.apoiionnewgame.xyz";

            PopActivityManager.Instance().InitData();
            // OnChangeLocalHost(2);
            OnLocalTestToChangeHost();
        }

        private void OnChangeLocalHost(int index)
        {
            
        }
        
        private void OnLocalTestToChangeHost()
        {
            mdropdown = transform.Find("Dropdown").GetComponent<Dropdown>();
            mdropdown.onValueChanged.AddListener((_value) =>
            {
                OnChangeLocalHost(_value);
            });
        }
        
         /// <summary>
        /// 初始化获得音乐状态
        /// </summary>
        /// <param name="args"></param>
        public void OnInitGameMusics()
        {
            if (PlayerPrefs.HasKey("LoaclEffect"))
            {
                GlobalUserItem.EffectAudioVolume = float.Parse(PlayerPrefs.GetString("LoaclEffect"));
            }
            if (PlayerPrefs.HasKey("LoaclMusic"))
            {
                GlobalUserItem.BGMVolume = float.Parse(PlayerPrefs.GetString("LoaclMusic"));
            }
            if (PlayerPrefs.HasKey("LoaclVibrate"))
            {
                GlobalUserItem.IsVibrateOpen = PlayerPrefs.GetInt("LoaclVibrate") == 1;
            }
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="args"></param>
        public override void OnShow(params object[] args)
        {
            base.OnShow(args);
            mLogin_Panel.gameObject.SetActive(true);
            mPhoneLogin_Panel.gameObject.SetActive(false);
            mRegister_Panel.gameObject.SetActive(false);
            mFindPwd_Panel.gameObject.SetActive(false);
            mPhone = "";
            if (PlayerPrefs.HasKey(GlobalUserItem.mPhoneKey))
            {
                mPhone = PlayerPrefs.GetString(GlobalUserItem.mPhoneKey);
            }
            if (PlayerPrefs.HasKey(GlobalUserItem.mPwdKey))
            {
                mPhonePwd = PlayerPrefs.GetString(GlobalUserItem.mPwdKey);
                mPhoneLogin_InputPwd.text = mPhonePwd;
            }

            mLogin_InputPhone.text = mPhone;
            mPhoneLogin_InputPhone.text = mPhone;
            mFindPwd_InputPhone.text = mPhone;
            
            transform.SetAsFirstSibling();
            OnInitGameMusics();
            PopActivityManager.Instance().OnBlockOutPopActView();
        }

        /// <summary>
        /// OnClose
        /// </summary>
        public override void OnClose(params object[] args)
        {
            base.OnClose(args);
        }

        private void OnInitLogin()
        {
            mLogin_Panel = transform.Find("Login").gameObject;
            mLogin_InputPhone = transform.Find("Login/inputPhone").GetComponent<InputField>();
            mLogin_btnLogin = transform.Find("Login/btnLogin").GetComponent<Button>();
            mLogin_btnRegister = transform.Find("Login/btnRegister").GetComponent<Button>();
            mLogin_btnGuest = transform.Find("Login/btnGuest").GetComponent<Button>();
           //Lamp = transform.Find("bg/Lamp").gameObject;
            Lamp = transform.Find("bg/Lamp").gameObject;
            //登录
            AddClickListener(mLogin_btnLogin, () =>
            {
                mPhoneLogin_Panel.gameObject.SetActive(true);
                // mPhoneLogin_InputPhone.text = "";
                // mPhoneLogin_InputPwd.text = "";
                mPhoneLogin_InputPhone.text = mLogin_InputPhone.text;
                mPhoneLogin_InputPwd.text = mPhonePwd;
            });
            
            //注册
            AddClickListener(mLogin_btnRegister, () =>
            {
                mRegister_Panel.gameObject.SetActive(true);
                mRegister_InputPhone.text = "";
                mRegister_InputPwd.text = "";
                mRegister_InputOpt.text = "";
            });
            
            //游客登录
            AddClickListener(mLogin_btnGuest, () =>
            {
                Utils.StartCoroutine(GetAdjustInfo());
            });

           // lamp_times = Vector3.Distance(Lamp.transform.GetChild(5).localPosition, new Vector3(1625, -39, 0))/ 2000;
            MoveUpdate();
        }
        int uu = 5;
        public void MoveUpdate() 
        {
            for (int i = 0; i < Lamp.transform.childCount; i++)
            {
                GameObject Lamp_obj = Lamp.transform.GetChild(i).gameObject;
                Vector3 StartPosi = Lamp_obj.transform.localPosition-new Vector3(18000,0,0);

                Lamp_obj.transform.DOLocalMove(StartPosi, 120).SetEase(Ease.Linear).OnComplete(() =>
                {

                    //Lamp_obj.transform.localPosition = Lamp_obj.transform.GetChild(uu).localPosition+new Vector3(Lamp_obj.transform.GetChild(uu).GetComponent<RectTransform>().sizeDelta.x+70,0,0);



                });
            }

        }

        private IEnumerator GetAdjustInfo()
        {
            UIManager.Instance.ShowWait(10);
            string adjustid = null;
            for (int i = 0; i < 10; i++)
            {
                yield return new WaitForSeconds(1f);
                // adjustid = AndroidManager.Instance().CallAndroidMethod();
                if (adjustid != null && adjustid != "")
                {
                    Debug.LogError("已经拿到AdjustId");
                    GlobalUserItem.szMachineID = adjustid;
                    break;
                }
            }
            GlobalUserItem.mPhoneNumber = null;
            GlobalUserItem.szPasswordID = "WHYK@foxuc.cn";
        }

        private void OnInitPhoneLogin()
        {
            mPhoneLogin_Panel = transform.Find("PhoneLogin").gameObject;
            mPhoneLogin_btnClose = transform.Find("PhoneLogin/btnClose").GetComponent<Button>();
            mPhoneLogin_InputPhone = transform.Find("PhoneLogin/inputPhone").GetComponent<InputField>();
            mPhoneLogin_InputPwd = transform.Find("PhoneLogin/inputPassword").GetComponent<InputField>();
            mPhoneLogin_btnForgetPwd = transform.Find("PhoneLogin/btnForgetPassword_l").GetComponent<Button>();
            mPhoneLogin_btnLogin = transform.Find("PhoneLogin/btnLogin").GetComponent<Button>();
            mPhoneLogin_btnShowPwd = transform.Find("PhoneLogin/btnShowPwd").GetComponent<Button>();
            mPhoneLogin_ShowPwd_Show = transform.Find("PhoneLogin/btnShowPwd/img_show_password").gameObject;
            mPhoneLogin_ShowPwd_Hide = transform.Find("PhoneLogin/btnShowPwd/img_hide_password").gameObject;
            
            //关闭
            AddClickListener(mPhoneLogin_btnClose, () =>
            {
                mPhoneLogin_Panel.SetActive(false);
            });
            
            //忘记密码
            AddClickListener(mPhoneLogin_btnForgetPwd, () =>
            {
                mFindPwd_Panel.SetActive(true);
                mFindPwd_InputPhone.text = "";
                mFindPwd_InputPwd.text = "";
                mFindPwd_InputOpt.text = "";
                mFindPwd_InputPhone.text = mPhoneLogin_InputPhone.text;
            });
            
            //登录
            AddClickListener(mPhoneLogin_btnLogin, () =>
            {
                string phone = mPhoneLogin_InputPhone.text;
                string pwd = mPhoneLogin_InputPwd.text;
                OnPhoneLogin(phone, pwd);
            });
            
            //显示密码
            AddClickListener(mPhoneLogin_btnShowPwd, () =>
            {
                // UIInput
                if (mPhoneLogin_InputPwd.contentType == InputField.ContentType.Password)
                {
                    mPhoneLogin_InputPwd.contentType = InputField.ContentType.Standard;
                    mPhoneLogin_ShowPwd_Show.SetActive(true);
                    mPhoneLogin_ShowPwd_Hide.SetActive(false);
                }
                else
                {
                    mPhoneLogin_InputPwd.contentType = InputField.ContentType.Password;
                    mPhoneLogin_ShowPwd_Show.SetActive(false);
                    mPhoneLogin_ShowPwd_Hide.SetActive(true);
                }
                mPhoneLogin_InputPwd.ForceLabelUpdate();
            });
        }

        private void OnPhoneLogin(string phone,string pwd)
        {
            if (string.IsNullOrEmpty(phone))
            {
                UIManager.Instance.ShowToolTips("The phone number can't be blank!");
                return;
            }
            if (phone.Length!=10)
            {
                UIManager.Instance.ShowToolTips("The phone number must be 10 digits!");
                return;
            }
            if (string.IsNullOrEmpty(pwd))
            {
                UIManager.Instance.ShowToolTips("The password can't be blank!");
                return;
            }
            if (pwd.Length!=6)
            {
                UIManager.Instance.ShowToolTips("The password must be 6 digits!");
                return;
            }
                
            GlobalUserItem.szPasswordID = pwd;
            // PlayerPrefs.SetString(GlobalUserItem.mPhoneKey,phone);
            GlobalUserItem.mPhoneNumber = phone;
            Debug.LogError("手机号码------------------"+phone);
        }
        
        private void OnInitRegister()
        {
            mRegister_Panel = transform.Find("Register").gameObject;
            mRegister_btnClose = transform.Find("Register/btnClose").GetComponent<Button>();
            mRegister_InputPhone = transform.Find("Register/inputPhone").GetComponent<InputField>();
            mRegister_InputPwd = transform.Find("Register/inputPassword").GetComponent<InputField>();
            mRegister_InputOpt = transform.Find("Register/inputOtp").GetComponent<InputField>();
            mRegister_btnShowPwd = transform.Find("Register/btnShowPwd").GetComponent<Button>();
            mRegister_btnOpt = transform.Find("Register/btnGetotp").GetComponent<Button>();
            mRegister_ClickOpt = transform.Find("Register/btnGetotp/optend").gameObject;
            mRegister_txtOpt = transform.Find("Register/btnGetotp/optend/Text").GetComponent<Text>();
            mRegister_btnRegister = transform.Find("Register/btnRegister").GetComponent<Button>();
            mRegister_ShowPwd_Show = transform.Find("Register/btnShowPwd/img_show_password").gameObject;
            mRegister_ShowPwd_Hide = transform.Find("Register/btnShowPwd/img_hide_password").gameObject;
            
            
            //关闭
            AddClickListener(mRegister_btnClose, () =>
            {
                mRegister_Panel.SetActive(false);
            });
            
            //显示密码
            AddClickListener(mRegister_btnShowPwd, () =>
            {
                // UIInput
                if (mRegister_InputPwd.contentType == InputField.ContentType.Password)
                {
                    mRegister_InputPwd.contentType = InputField.ContentType.Standard;
                    mRegister_ShowPwd_Show.SetActive(true);
                    mRegister_ShowPwd_Hide.SetActive(false);
                }
                else
                {
                    mRegister_InputPwd.contentType = InputField.ContentType.Password;
                    mRegister_ShowPwd_Show.SetActive(false);
                    mRegister_ShowPwd_Hide.SetActive(true);
                }
                mRegister_InputPwd.ForceLabelUpdate();
            });
            
            //发送获取验证码
            AddClickListener(mRegister_btnOpt, () =>
            {
                string phonenum = mRegister_InputPhone.text;
                if (string.IsNullOrEmpty(phonenum))
                {
                    UIManager.Instance.ShowToolTips("The phone number can't be blank!");
                    return;
                }

                if (phonenum.Length != 10)
                {
                    UIManager.Instance.ShowToolTips("The phone number must be 10 digits!");
                    return;
                }

                if (mRegister_ClickOpt.gameObject.activeSelf)
                {
                    return;
                }

                mRegister_ClickOpt.SetActive(true);
                mRegister_txtOpt.text = "1";
                DOTween.To(() => int.Parse(mRegister_txtOpt.text), x => mRegister_txtOpt.text = (60-x).ToString(), 60, 60).SetEase(Ease.Linear).OnComplete(() =>
                {
                    mRegister_ClickOpt.SetActive(false);
                });
            });
            
            //注册
            AddClickListener(mRegister_btnRegister, () =>
            {
                string phoneNum = mRegister_InputPhone.text;
                string pwd = mRegister_InputPwd.text;
                string yzm = mRegister_InputOpt.text;
                uint yqr = 0;
                if (string.IsNullOrEmpty(phoneNum))
                {
                    UIManager.Instance.ShowToolTips("The phone number can't be blank!");
                    return;
                }
                if (phoneNum.Length != 10)
                {
                    UIManager.Instance.ShowToolTips("The phone number must be 10 digits!");
                    return;
                }
                
                if (string.IsNullOrEmpty(pwd))
                {
                    UIManager.Instance.ShowToolTips("The password can't be blank!");
                    return;
                }
                if (pwd.Length != 6)
                {
                    UIManager.Instance.ShowToolTips("The password must be 6 digits!");
                    return;
                }
                
                if (string.IsNullOrEmpty(yzm))
                {
                    UIManager.Instance.ShowToolTips("The OTP can't be blank!");
                    return;
                }
                if (yzm.Length != 6)
                {
                    UIManager.Instance.ShowToolTips("The OTP must be 6 digits!");
                    return;
                }

                yqr = OnGetYQM();
                GlobalUserItem.szPasswordID = pwd;
                string clickLabel = ""; //andoridManager:GetclickLabel()
                if (clickLabel.Length >= 1)
                {
                    yqr = uint.Parse(clickLabel) << 2;
                }

                if (yqr == 0)
                {
                    string uu = "";//andoridManager:GetClipboardManager()
                    if (uu != "")
                    {
                        // local copyList={}
                        // for word in string.gmatch(uu, "[^_]+") do
                        //     print(word)
                        // table.insert(copyList,word)
                        // end
                        // if copyList[1]=="CashRummy"then
                        // logError("copy="..copyList[#copyList])
                        // --yqm=copyList[#copyList]
                        // yqm=Decode_GameId(copyList[#copyList])
                        // end 
                    }
                    
                }

                // PlayerPrefs.SetString(GlobalUserItem.mPhoneKey,phoneNum);
                GlobalUserItem.mPhoneNumber = phoneNum;
                Debug.LogError("注册账号："+phoneNum);
            });
        }

        /// <summary>
        /// 获取邀请码
        /// </summary>
        /// <returns></returns>
        private uint OnGetYQM()
        {
            // string yqm = AndroidManager.Instance().GetclickLabel();
            // Debug.LogError("邀请人信息：" + yqm);
            // if (string.IsNullOrEmpty(yqm) || yqm == ""|| yqm=="null")
            // {
            //     Debug.Log("没有邀请人信息");
            //     string uu = AndroidManager.Instance().GetClipboardManager();
            //
            //     Debug.LogError("获取粘贴板信息===========" + uu);
            //     if (string.IsNullOrWhiteSpace(uu) == false&& uu!="null")
            //     {
            //         string[] copyarr = uu.Split("_");
            //         if (copyarr[0] == "CashRummy")
            //         {
            //             return Tool.Decode_GameId(copyarr[copyarr.Length - 1]);
            //         }
            //     }
            // }
            // else
            // {
            //     Debug.LogError("=================来到编码====================");
            //     if (yqm.Length > 0&& yqm!="null")
            //     {
            //         return Tool.Decode_GameId(yqm);
            //     }
            // }
            return 0;
        }



        private void OnInitFindPwd()
        {
            mFindPwd_Panel = transform.Find("FindPassword").gameObject;
            mFindPwd_btnClose = transform.Find("FindPassword/btnClose").GetComponent<Button>();
            mFindPwd_InputPhone = transform.Find("FindPassword/inputPhone").GetComponent<InputField>();
            mFindPwd_InputPwd = transform.Find("FindPassword/inputPassword").GetComponent<InputField>();
            mFindPwd_InputOpt = transform.Find("FindPassword/inputOtp").GetComponent<InputField>();
            mFindPwd_btnShowPwd = transform.Find("FindPassword/btn_show_password_fp").GetComponent<Button>();
            mFindPwd_btnOpt = transform.Find("FindPassword/btnGetotp").GetComponent<Button>();
            mFindPwd_ClickOpt = transform.Find("FindPassword/btnGetotp/optend").gameObject;
            mFindPwd_txtOpt = transform.Find("FindPassword/btnGetotp/optend/Text").GetComponent<Text>();
            mFindPwd_btnModify = transform.Find("FindPassword/btnModify").GetComponent<Button>();
            mFindPwd_ShowPwd_Show = transform.Find("FindPassword/btn_show_password_fp/img_show_password").gameObject;
            mFindPwd_ShowPwd_Hide = transform.Find("FindPassword/btn_show_password_fp/img_hide_password").gameObject;
            
             
            //关闭
            AddClickListener(mFindPwd_btnClose, () =>
            {
                mFindPwd_Panel.SetActive(false);
            });
            
            //显示密码
            AddClickListener(mFindPwd_btnShowPwd, () =>
            {
                // UIInput
                if (mFindPwd_InputPwd.contentType == InputField.ContentType.Password)
                {
                    mFindPwd_InputPwd.contentType = InputField.ContentType.Standard;
                    mFindPwd_ShowPwd_Show.SetActive(true);
                    mFindPwd_ShowPwd_Hide.SetActive(false);
                }
                else
                {
                    mFindPwd_InputPwd.contentType = InputField.ContentType.Password;
                    mFindPwd_ShowPwd_Show.SetActive(false);
                    mFindPwd_ShowPwd_Hide.SetActive(true);
                }
                mFindPwd_InputPwd.ForceLabelUpdate();
            });
            
            //发送获取验证码
            AddClickListener(mFindPwd_btnOpt, () =>
            {
                string phonenum = mFindPwd_InputPhone.text;
                if (string.IsNullOrEmpty(phonenum))
                {
                    UIManager.Instance.ShowToolTips("The phone number can't be blank!");
                    return;
                }

                if (phonenum.Length != 10 && phonenum.Length != 13)
                {
                    UIManager.Instance.ShowToolTips("The phone number must be 10 digits!");
                    return;
                }

                if (mFindPwd_ClickOpt.gameObject.activeSelf)
                {
                    return;
                }

                misTimeend = true;
                mFindPwd_ClickOpt.SetActive(true);
                mFindPwd_txtOpt.text = "1";
                DOTween.To(() => int.Parse(mFindPwd_txtOpt.text), x => mFindPwd_txtOpt.text = (60-x).ToString(), 60, 60).SetEase(Ease.Linear).OnComplete(() =>
                {
                    mFindPwd_ClickOpt.SetActive(false);
                });
            });
            
            //  Modify登录
            AddClickListener(mFindPwd_btnModify, () =>
            {
                string phoneNum = mFindPwd_InputPhone.text;
                string pwd = mFindPwd_InputPwd.text;
                string yzm = mFindPwd_InputOpt.text;
                
                if (string.IsNullOrEmpty(phoneNum))
                {
                    UIManager.Instance.ShowToolTips("The phone number can't be blank!");
                    return;
                }
                if (phoneNum.Length != 10 && phoneNum.Length != 13)
                {
                    UIManager.Instance.ShowToolTips("The phone number must be 10 digits!");
                    return;
                }
                
                if (string.IsNullOrEmpty(pwd))
                {
                    UIManager.Instance.ShowToolTips("The password can't be blank!");
                    return;
                }
                if (pwd.Length != 6)
                {
                    UIManager.Instance.ShowToolTips("The password must be 6 digits!");
                    return;
                }
                
                if (string.IsNullOrEmpty(yzm))
                {
                    UIManager.Instance.ShowToolTips("The OTP can't be blank!");
                    return;
                }
                if (yzm.Length != 6)
                {
                    UIManager.Instance.ShowToolTips("The OTP must be 6 digits!");
                    return;
                }
                
                // PlayerPrefs.SetString(GlobalUserItem.mPhoneKey,phoneNum);
                GlobalUserItem.mPhoneNumber = phoneNum;
                
                GlobalUserItem.szPasswordID = pwd;
            });
        }
    }
}